package com.liyuan.yiqixing.controller;

import com.alibaba.fastjson.JSONObject;
import com.liyuan.yiqixing.model.Comment;
import com.liyuan.yiqixing.model.Discussion;
import com.liyuan.yiqixing.model.Page;
import com.liyuan.yiqixing.model.ResultJson;
import com.liyuan.yiqixing.service.CommentService;
import com.liyuan.yiqixing.service.DiscussionService;
import com.liyuan.yiqixing.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class DiscussionController {
    @Value("${discussion.sacle}")
    private Integer scale;

    @Autowired
    DiscussionService discussionService;
    @Autowired
    PageService pageService;
    /**
     * 通过 分类，每页大小，当前页码 获取discussions
     * @param classification
     * @param currentPage
     * @return
     */
    @PostMapping("/classification/{classification}/{currentPage}")
    public ResultJson share(@PathVariable("classification")String classification,
            @PathVariable("currentPage")Integer currentPage){
        Discussion[] discussions =discussionService.retrieveDiscussions(currentPage,scale,classification);
        Page page = pageService.paging(currentPage,scale,discussionService.sum(classification));
        return new ResultJson(200,"get share info ->page:"+currentPage,new Object[]{discussions,page});
    }
    @GetMapping("/discussion/{dicussionId}")
    public void discussion(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/discussionItem.html").forward(request,response);
    }

    @PostMapping("/discussion/{discussionId}")
    public ResultJson discussionItem(@PathVariable("discussionId")Integer id){
        Discussion discussion = discussionService.retrieveDiscussion(id);
        return new ResultJson(200,"get discussion->"+id+"success!!",discussion);
    }

    @Autowired
    CommentService commentService;
    @PostMapping("/discussion/retrieveComments/")
    public ResultJson<Object> retrieveComments(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer type = jsonObject.getInteger("type");
        Integer targetId = jsonObject.getInteger("targetId");
        Comment[] comments =commentService.retrieveComments(type,targetId);
        return new ResultJson<>(200,"Retrieve comments success!!!",comments);
    }

}
